import {useRef, useState} from "react";
import {useRequest} from "@/utils/useRequest.tsx";
import Modal, {ModalInstanceType} from "@/conponments/Modal";

type ResponseType = {
    token: string
    name: string
}

function Register() {
    const [userName, setUserName] = useState('')
    const [phoneNumber, setPhoneNumber] = useState('')
    const [password, setPassword] = useState('')
    const [checkPassword, setCheckPassword] = useState('')
    const modalRef = useRef<ModalInstanceType>(null)
    const {data, request} = useRequest<ResponseType>()
    console.log(data)

    // 点击注册
    async function handleSubmitBtnClick() {
        if (!userName) {
            modalRef.current?.showMessage('请输入用户名')
            return
        }
        if (!phoneNumber) {
            modalRef.current?.showMessage('请输入手机号')
            return
        }
        if (!password) {
            modalRef.current?.showMessage('请输入密码')
            return
        }
        if (!checkPassword) {
            modalRef.current?.showMessage('请输入确认密码')
            return
        }
        if (password !== checkPassword) {
            modalRef.current?.showMessage('两次密码不一致')
            return
        }
        const data = await request({
            url: '/api/register', method: 'POST', data: {phoneNumber, password}
        })
        console.log(data)
    }

    return <>
        <div className="form">
            <div className="form-item">
                <div className="form-item-title">用户名</div>
                <input type="text" className="form-item-content" placeholder="请输入用户名" value={userName}
                       onChange={(e) => setUserName(e.target.value)}/>
            </div>
            <div className="form-item">
                <div className="form-item-title">手机号</div>
                <input type="text" className="form-item-content" placeholder="请输入手机号" value={phoneNumber}
                       onChange={(e) => setPhoneNumber(e.target.value)}/>
            </div>
            <div className="form-item">
                <div className="form-item-title">密码</div>
                <input type="password" className="form-item-content" placeholder="请输入密码" value={password}
                       onChange={(e) => setPassword(e.target.value)}/>
            </div>
            <div className="form-item">
                <div className="form-item-title">确认密码</div>
                <input type="password" className="form-item-content" placeholder="请输入确认密码" value={checkPassword}
                       onChange={(e) => setCheckPassword(e.target.value)}/>
            </div>
        </div>
        <div className="submit" onClick={handleSubmitBtnClick}>
            登陆
        </div>
        <Modal ref={modalRef}/>
    </>
}

export default Register

